<template>
  <div class="basic-info">
    <div class="form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        size="large"
        @validate="handleFormValidate"
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="工作流名称" prop="name" required>
              <el-input
                v-model="formData.name"
                placeholder="请输入工作流名称"
                clearable
                maxlength="50"
                show-word-limit
                @blur="handleNameBlur"
                :loading="isValidatingName"
              />
              <div v-if="nameValidationMessage" class="validation-message" :class="{ 'error': nameValidationMessage.includes('已存在') || nameValidationMessage.includes('失败') }">
                {{ nameValidationMessage }}
              </div>
              <div class="field-hint">
                工作流的唯一标识名称，用于区分不同的工作流程
              </div>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="版本号" prop="version">
              <el-input
                v-model="formData.version"
                placeholder="请输入版本号"
                clearable
                maxlength="20"
              />
              <div class="field-hint">
                工作流版本号，建议使用语义化版本格式（如：1.0.0）
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="工作流简介" prop="description" required>
          <el-input
            v-model="formData.description"
            type="textarea"
            placeholder="请输入工作流的详细描述，包括用途、适用场景等"
            :rows="4"
            maxlength="500"
            show-word-limit
            resize="vertical"
          />
          <div class="field-hint">
            详细描述工作流的用途、适用场景和主要功能
          </div>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-input
            :model-value="formatDate(formData.createdAt)"
            readonly
            disabled
          />
          <div class="field-hint">
            工作流创建的时间，系统自动生成
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表单预览卡片 -->
    <div class="preview-container">
      <el-card class="preview-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">配置预览</span>
            <el-tag :type="isFormValid ? 'success' : 'warning'">
              {{ isFormValid ? '配置有效' : '配置不完整' }}
            </el-tag>
          </div>
        </template>
        
        <div class="preview-content">
          <div class="preview-item">
            <label>工作流名称：</label>
            <span class="preview-value">{{ formData.name || '未设置' }}</span>
          </div>
          <div class="preview-item">
            <label>版本号：</label>
            <span class="preview-value">{{ formData.version || '未设置' }}</span>
          </div>
          <div class="preview-item">
            <label>工作流简介：</label>
            <span class="preview-value">{{ formData.description || '未设置' }}</span>
          </div>
          <div class="preview-item">
            <label>创建时间：</label>
            <span class="preview-value">{{ formatDate(formData.createdAt) }}</span>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { BasicInfo } from '@/types'
import { validateWorkflowNameUniqueness, validateBasicInfo, addWorkflowName } from '@/services/workflowValidation'

// Props and Emits
interface Props {
  modelValue: BasicInfo
}

interface Emits {
  (e: 'update:modelValue', value: BasicInfo): void
  (e: 'validate', isValid: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// Refs
const formRef = ref<FormInstance>()
const isValidatingName = ref(false)
const nameValidationMessage = ref('')

// Form data
const formData = ref<BasicInfo>({
  name: '',
  description: '',
  version: '1.0.0',
  createdAt: new Date(),
})

// Custom validator for workflow name uniqueness
const validateNameUniqueness = async (rule: any, value: string, callback: any) => {
  if (!value || !value.trim()) {
    callback()
    return
  }

  isValidatingName.value = true
  nameValidationMessage.value = '正在验证名称唯一性...'

  try {
    const isUnique = await validateWorkflowNameUniqueness(value.trim())
    isValidatingName.value = false
    
    if (!isUnique) {
      nameValidationMessage.value = '该工作流名称已存在，请使用其他名称'
      callback(new Error('该工作流名称已存在，请使用其他名称'))
    } else {
      nameValidationMessage.value = ''
      callback()
    }
  } catch (error) {
    isValidatingName.value = false
    nameValidationMessage.value = '验证失败，请重试'
    callback(new Error('验证失败，请重试'))
  }
}

// Form validation rules
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入工作流名称', trigger: 'blur' },
    { min: 2, max: 50, message: '工作流名称长度应在 2-50 个字符之间', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9\u4e00-\u9fa5_-]+$/, 
      message: '工作流名称只能包含中英文、数字、下划线和连字符', 
      trigger: 'blur' 
    },
    { validator: validateNameUniqueness, trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请输入工作流简介', trigger: 'blur' },
    { min: 10, max: 500, message: '工作流简介长度应在 10-500 个字符之间', trigger: 'blur' },
  ],
  version: [
    { 
      pattern: /^\d+\.\d+\.\d+$/, 
      message: '版本号格式应为 x.y.z（如：1.0.0）', 
      trigger: 'blur' 
    },
  ],
}

// Computed
const isFormValid = computed(() => {
  return formData.value.name.trim() !== '' && 
         formData.value.description.trim() !== '' &&
         formData.value.name.length >= 2 &&
         formData.value.description.length >= 10
})

// Methods
const formatDate = (date: Date) => {
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  })
}

const handleFormValidate = (prop: string, isValid: boolean) => {
  // 当表单字段验证时触发
  validateForm()
}

const handleNameBlur = () => {
  // 工作流名称失焦时会自动触发验证规则中的唯一性验证
  if (formData.value.name.trim()) {
    console.log('验证工作流名称唯一性:', formData.value.name)
  }
}

const validateForm = async () => {
  if (!formRef.value) return false
  
  try {
    await formRef.value.validate()
    emit('validate', isFormValid.value && !isValidatingName.value)
    return true
  } catch {
    emit('validate', false)
    return false
  }
}

const saveBasicInfo = async () => {
  try {
    // 先进行表单验证
    const isValid = await validateForm()
    if (!isValid) {
      ElMessage.error('请先完成表单验证')
      return false
    }

    // 进行完整性验证
    const validationResult = validateBasicInfo(formData.value)
    if (!validationResult.isValid) {
      ElMessage.error(validationResult.errors[0])
      return false
    }

    // 模拟保存操作
    console.log('保存基本信息:', formData.value)
    
    // 将工作流名称添加到已存在列表（模拟保存后的操作）
    if (formData.value.name.trim()) {
      addWorkflowName(formData.value.name.trim())
    }

    ElMessage.success('基本信息保存成功')
    return true
  } catch (error) {
    console.error('保存基本信息失败:', error)
    ElMessage.error('保存失败，请重试')
    return false
  }
}

const resetForm = () => {
  formRef.value?.resetFields()
  formData.value = {
    name: '',
    description: '',
    version: '1.0.0',
    createdAt: new Date(),
  }
  nameValidationMessage.value = ''
  isValidatingName.value = false
}

// Watch for prop changes
watch(() => props.modelValue, (newValue) => {
  if (newValue) {
    formData.value = { ...newValue }
  }
}, { immediate: true, deep: true })

// Watch for form data changes
watch(formData, (newValue) => {
  emit('update:modelValue', { ...newValue })
  // 使用nextTick避免无限循环
  nextTick(() => {
    validateForm()
  })
}, { deep: true })

// Watch for form validity changes
watch(isFormValid, (newValue) => {
  emit('validate', newValue)
}, { flush: 'post' })

// Lifecycle
onMounted(() => {
  // 初始化时进行一次验证
  validateForm()
})

// Expose methods for parent component
defineExpose({
  validate: validateForm,
  save: saveBasicInfo,
  reset: resetForm,
  resetFields: () => formRef.value?.resetFields(),
})
</script>

<style scoped>
.basic-info {
  display: flex;
  gap: 24px;
  min-height: 500px;
}

.form-container {
  flex: 2;
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.preview-container {
  flex: 1;
  min-width: 300px;
}

.preview-card {
  height: fit-content;
  position: sticky;
  top: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-weight: 500;
  color: #303133;
}

.preview-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.preview-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.preview-item label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.preview-value {
  font-size: 14px;
  color: #303133;
  word-break: break-word;
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 4px;
  min-height: 20px;
}

.field-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.validation-message {
  font-size: 12px;
  margin-top: 4px;
  line-height: 1.4;
  color: #409eff;
}

.validation-message.error {
  color: #f56c6c;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .basic-info {
    flex-direction: column;
  }
  
  .preview-container {
    min-width: auto;
  }
  
  .preview-card {
    position: static;
  }
}

@media (max-width: 768px) {
  .form-container {
    padding: 16px;
  }
  
  :deep(.el-col) {
    margin-bottom: 0;
  }
  
  :deep(.el-row) {
    margin: 0;
  }
  
  .el-col {
    width: 100% !important;
    max-width: 100% !important;
    flex: 0 0 100% !important;
  }
}

/* Element Plus 样式覆盖 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

:deep(.el-input__wrapper) {
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-textarea__inner) {
  transition: all 0.3s ease;
}

:deep(.el-textarea__inner:hover) {
  border-color: #c0c4cc;
}
</style>